<template>
  <div class="dashboard-page">
    <!-- 数据概览头部 -->
    <div class="page-header">
      <h1>数据概览</h1>
    </div>

    <!-- 核心指标卡片 -->
    <div class="stats-cards">
      <div class="stat-card">
        <div class="stat-icon user-stat">
          <el-icon>
            <User />
          </el-icon>
        </div>
        <div class="stat-info">
          <div class="stat-number">{{ formatNumber(stats.totalUsers) }}</div>
          <div class="stat-label">总用户数</div>
        </div>
      </div>

      <div class="stat-card">
        <div class="stat-icon active-stat">
          <el-icon>
            <HelpFilled />
          </el-icon>
        </div>
        <div class="stat-info">
          <div class="stat-number">{{ formatNumber(stats.totalCircles) }}</div>
          <div class="stat-label">总圈子数</div>
        </div>
      </div>

      <div class="stat-card">
        <div class="stat-icon post-stat">
          <el-icon>
            <Document />
          </el-icon>
        </div>
        <div class="stat-info">
          <div class="stat-number">{{ formatNumber(stats.totalPosts) }}</div>
          <div class="stat-label">总动态数</div>
        </div>
      </div>

      <div class="stat-card">
        <div class="stat-icon verify-stat">
          <el-icon>
            <Avatar />
          </el-icon>
        </div>
        <div class="stat-info">
          <div class="stat-number">{{ formatNumber(stats.totalAlumnis) }}</div>
          <div class="stat-label">总校友数</div>
        </div>
      </div>
    </div>

    <!-- 图表区域 -->
    <div class="charts-section">
      <div class="chart-row">
        <!-- 用户增长趋势 -->
        <el-card class="chart-card">
          <template #header>
            <div class="chart-header">
              <span>用户增长趋势</span>
              <el-radio-group v-model="userChartRange" size="small">
                <el-radio-button label="week">本周</el-radio-button>
                <el-radio-button label="month">本月</el-radio-button>
                <el-radio-button label="quarter">本季度</el-radio-button>
              </el-radio-group>
            </div>
          </template>
          <div class="chart-container">
            <div class="chart-demo-bar">
              <div class="chart-bars">
                <div v-for="(item, index) in userGrowthData" :key="index" class="chart-bar-wrapper">
                  <div class="chart-bar" :style="{ height: (item.value / maxUserValue) * 200 + 'px' }"
                    :title="item.label + ': ' + item.value">
                    <span class="bar-value">{{ item.value }}</span>
                  </div>
                  <span class="bar-label">{{ item.label }}</span>
                </div>
              </div>
            </div>
          </div>
        </el-card>

        <!-- 圈子类型分布 -->
        <el-card class="chart-card">
          <template #header>
            <div class="chart-header">
              <span>圈子类型分布</span>
            </div>
          </template>
          <div class="chart-container">
            <div class="pie-chart-demo" v-if="circleStats.typeStats && circleStats.typeStats.length > 0">
              <div class="pie-chart" :style="getPieChartStyle">
                <div v-for="(item, index) in circleStats.typeStats" :key="index" class="pie-segment">
                  <div class="segment-label" :style="getSegmentLabelStyle(index)">
                    <span class="segment-color" :style="{ backgroundColor: getColor(index) }"></span>
                    {{ item.type }} ({{ item.count }})
                  </div>
                </div>
              </div>
              <div class="pie-center">
                <div class="total-count">{{ circleStats.totalCircles }}</div>
                <div class="total-label">总圈子数</div>
              </div>
            </div>
            <div v-else class="no-data">
              <el-empty description="暂无圈子数据" :image-size="80" />
            </div>
          </div>
        </el-card>
      </div>

      <div class="chart-row">
        <!-- 活跃度分析 -->
        <el-card class="chart-card full-width">
          <template #header>
            <div class="chart-header">
              <span>用户活跃度分析</span>
              <el-select v-model="activityMetric" placeholder="选择指标" style="width: 120px">
                <el-option label="访问量" value="visits" />
                <el-option label="停留时长" value="duration" />
                <el-option label="互动次数" value="interactions" />
              </el-select>
            </div>
          </template>
          <div class="chart-container">
            <div class="line-chart-demo">
              <div class="line-chart">
                <div v-for="(point, index) in activityData" :key="index" class="data-point"
                  :style="{ left: (index * 15) + '%', bottom: (point.value / maxActivityValue) * 180 + 'px' }">
                  <div class="point-value">{{ point.value }}</div>
                </div>
                <div class="line"></div>
              </div>
              <div class="line-labels">
                <span v-for="point in activityData" :key="point.label" class="line-label">
                  {{ point.label }}
                </span>
              </div>
            </div>
          </div>
        </el-card>
      </div>
    </div>

    <!-- 实时数据 -->
    <div class="realtime-section">
      <el-card>
        <template #header>
          <div class="section-header">
            <h3>实时数据监控</h3>
            <div class="realtime-indicator">
              <el-badge is-dot type="success" />
              <span class="indicator-text">实时更新中</span>
            </div>
          </div>
        </template>
        <div class="realtime-stats">
          <div class="realtime-stat">
            <div class="realtime-value">{{ realtimeData.onlineUsers }}</div>
            <div class="realtime-label">当前在线用户</div>
          </div>
          <div class="realtime-stat">
            <div class="realtime-value">{{ realtimeData.newRegisters }}</div>
            <div class="realtime-label">今日新注册</div>
          </div>
          <div class="realtime-stat">
            <div class="realtime-value">{{ realtimeData.newPosts }}</div>
            <div class="realtime-label">今日新动态</div>
          </div>
          <div class="realtime-stat">
            <div class="realtime-value">{{ realtimeData.systemLoad }}%</div>
            <div class="realtime-label">系统负载</div>
          </div>
        </div>
      </el-card>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import {
  User,
  Document,
} from '@element-plus/icons-vue'
import { useUserStore } from '@/stores/user'
import { usePostsStore } from '@/stores/posts'
import { useCirclesStore } from '@/stores/circles'
import { useAlumniStore } from '@/stores/alumni'

// 响应式数据
const userChartRange = ref('week')
const activityMetric = ref('visits')

const userStore = useUserStore()
const postStore = usePostsStore()
const circleStore = useCirclesStore()
const alumniStore = useAlumniStore()
// 统计数据
const stats = reactive({
  totalUsers: 12458,
  totalCircles: 2347,
  totalPosts: 356,
  totalAlumnis: 0,
})

// 圈子统计信息
const circleStats = reactive({
  totalCircles: 0,
  typeStats: [],
  topCircles: []
})

// 颜色配置
const chartColors = ['#409EFF', '#67C23A', '#E6A23C', '#F56C6C', '#909399', '#8E44AD', '#16A085', '#E74C3C']

// 计算属性 - 饼图样式
const getPieChartStyle = computed(() => {
  if (!circleStats.typeStats || circleStats.typeStats.length === 0) {
    return ''
  }

  let conicGradient = 'conic-gradient('
  let accumulatedPercentage = 0

  circleStats.typeStats.forEach((item, index) => {
    const percentage = (item.count / circleStats.totalCircles) * 100
    const start = accumulatedPercentage + '%'
    accumulatedPercentage += percentage
    const end = accumulatedPercentage + '%'

    conicGradient += `${getColor(index)} ${start} ${end}`

    if (index < circleStats.typeStats.length - 1) {
      conicGradient += ', '
    }
  })

  conicGradient += ')'

  return {
    background: conicGradient
  }
})

// 计算属性 - 标签位置
const getSegmentLabelStyle = (index) => {
  const totalItems = circleStats.typeStats.length
  const angle = (360 / totalItems) * index
  const radius = 120 // 饼图半径

  // 计算标签位置（在饼图外部）
  const labelAngle = angle + (360 / totalItems / 2) // 标签在扇形中间
  const radian = (labelAngle * Math.PI) / 180
  const x = Math.cos(radian) * (radius + 40) // 距离饼图中心40px
  const y = Math.sin(radian) * (radius + 40)

  return {
    position: 'absolute',
    left: `calc(50% + ${x}px)`,
    top: `calc(50% + ${y}px)`,
    transform: 'translate(-50%, -50%)',
    fontSize: '12px',
    whiteSpace: 'nowrap'
  }
}

// 获取颜色
const getColor = (index) => {
  return chartColors[index % chartColors.length]
}

// 用户增长数据
const userGrowthData = ref([
  { label: '周一', value: 145 },
  { label: '周二', value: 189 },
  { label: '周三', value: 167 },
  { label: '周四', value: 234 },
  { label: '周五', value: 198 },
  { label: '周六', value: 156 },
  { label: '周日', value: 123 }
])

// 内容分布数据
const contentDistribution = ref([
  { name: '动态', value: 3560, percentage: 42, color: '#409EFF' },
  { name: '圈子', value: 1890, percentage: 22, color: '#67C23A' },
  { name: '招聘', value: 1250, percentage: 15, color: '#E6A23C' },
  { name: '二手', value: 890, percentage: 11, color: '#F56C6C' },
  { name: '其他', value: 862, percentage: 10, color: '#909399' }
])

// 活跃度数据
const activityData = ref([
  { label: '00:00', value: 120 },
  { label: '04:00', value: 80 },
  { label: '08:00', value: 450 },
  { label: '12:00', value: 680 },
  { label: '16:00', value: 520 },
  { label: '20:00', value: 380 }
])

// 实时数据
const realtimeData = reactive({
  onlineUsers: 342,
  newRegisters: 28,
  newPosts: 45,
  systemLoad: 65
})

const getUserTotal = async () => {
  const result = await userStore.getUserListAction()
  stats.totalUsers = result.data.pagination.total
}

const getPostTotal = async () => {
  const result = await postStore.fetchPosts()
  stats.totalPosts = result.data.pagination.total
}

const getCircleTotal = async () => {
  const result = await circleStore.fetchCirclesAction()
  stats.totalCircles = result.data.pagination.total
}

const getAlumniTotal = async () => {
  const result = await alumniStore.fetchAlumnisAction()
  stats.totalAlumnis = result.data.pagination.total
}
// 计算属性
const maxUserValue = computed(() => {
  return Math.max(...userGrowthData.value.map(item => item.value))
})

const maxActivityValue = computed(() => {
  return Math.max(...activityData.value.map(item => item.value))
})

// 方法
const formatNumber = (num) => {
  return num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',')
}

// 获取圈子统计信息
const getCircleStats = async () => {
  try {
    const result = await circleStore.fetchCircleStatsAction()
    if (result.code === 0) {
      Object.assign(circleStats, result.data)
      stats.totalCircles = result.data.totalCircles
    }
  } catch (error) {
    console.error('获取圈子统计信息失败:', error)
    ElMessage.error('获取圈子统计信息失败')
  }
}
onMounted(() => {
  getUserTotal()
  getPostTotal()
  getCircleTotal()
  getAlumniTotal()
  getCircleStats()
})
</script>

<style scoped>
.dashboard-page {
  padding: 0;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.page-header h1 {
  font-size: 24px;
  color: #303133;
  margin: 0;
}

/* 统计卡片样式 */
.stats-cards {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
  gap: 16px;
  margin-bottom: 24px;
}

.stat-card {
  background: #ffffff;
  border-radius: 12px;
  padding: 24px;
  display: flex;
  align-items: center;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
}

.stat-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
}

.stat-icon {
  width: 60px;
  height: 60px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 16px;
  color: white;
  font-size: 24px;
}

.user-stat {
  background: linear-gradient(135deg, #409EFF, #79bbff);
}

.active-stat {
  background: linear-gradient(135deg, #67C23A, #95d475);
}

.post-stat {
  background: linear-gradient(135deg, #E6A23C, #eebe77);
}

.verify-stat {
  background: linear-gradient(135deg, #F56C6C, #f89898);
}

.stat-info {
  flex: 1;
}

.stat-number {
  font-size: 32px;
  font-weight: bold;
  color: #303133;
  margin-bottom: 4px;
}

.stat-label {
  font-size: 14px;
  color: #909399;
  margin-bottom: 4px;
}

.stat-compare {
  font-size: 12px;
  color: #606266;
}

.trend {
  font-weight: 500;
}

.trend.up {
  color: #F56C6C;
}

.trend.down {
  color: #67C23A;
}

.trend.warning {
  color: #E6A23C;
}

/* 图表区域样式 */
.charts-section {
  margin-bottom: 24px;
}

.chart-row {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 16px;
  margin-bottom: 16px;
}

.chart-card.full-width {
  grid-column: 1 / -1;
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.chart-container {
  height: 300px;
  display: flex;
  align-items: center;
  justify-content: center;
}

/* 柱状图样式 */
.chart-demo-bar {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.chart-bars {
  display: flex;
  align-items: flex-end;
  justify-content: space-around;
  height: 200px;
  margin-bottom: 20px;
}

.chart-bar-wrapper {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
}

.chart-bar {
  width: 40px;
  background: linear-gradient(to top, #409EFF, #79bbff);
  border-radius: 4px 4px 0 0;
  display: flex;
  align-items: flex-start;
  justify-content: center;
  padding-top: 8px;
  transition: all 0.3s;
  cursor: pointer;
  position: relative;
  min-height: 20px;
}

.chart-bar:hover {
  background: linear-gradient(to top, #337ecc, #409EFF);
  transform: scale(1.05);
}

.bar-value {
  color: white;
  font-size: 12px;
  font-weight: bold;
}

.bar-label {
  font-size: 12px;
  color: #909399;
}

/* 折线图样式 */
.line-chart-demo {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.line-chart {
  position: relative;
  height: 200px;
  margin-bottom: 20px;
  border-bottom: 1px solid #e4e7ed;
}

.data-point {
  position: absolute;
  width: 8px;
  height: 8px;
  background: #409EFF;
  border-radius: 50%;
  transform: translate(-50%, 50%);
}

.data-point::before {
  content: '';
  position: absolute;
  width: 16px;
  height: 16px;
  background: rgba(64, 158, 255, 0.2);
  border-radius: 50%;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

.point-value {
  position: absolute;
  top: -25px;
  left: 50%;
  transform: translateX(-50%);
  font-size: 12px;
  color: #409EFF;
  font-weight: 500;
}

.line {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  height: 2px;
  background: linear-gradient(90deg, #409EFF, transparent);
}

.line-labels {
  display: flex;
  justify-content: space-between;
}

.line-label {
  font-size: 12px;
  color: #909399;
}

/* 实时数据样式 */
.realtime-section {
  margin-bottom: 24px;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.realtime-indicator {
  display: flex;
  align-items: center;
  gap: 8px;
}

.indicator-text {
  font-size: 14px;
  color: #67C23A;
}

.realtime-stats {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 20px;
}

.realtime-stat {
  text-align: center;
  padding: 20px;
  background: #f9f9f9;
  border-radius: 8px;
}

.realtime-value {
  font-size: 32px;
  font-weight: bold;
  color: #409EFF;
  margin-bottom: 8px;
}

.realtime-label {
  font-size: 14px;
  color: #909399;
}

/* 底部区域样式 */
.bottom-section {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 16px;
}

.quick-actions-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 16px;
}

.quick-action-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20px;
  border: 1px solid #f0f0f0;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s;
}

.quick-action-item:hover {
  border-color: #409EFF;
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.1);
}

.action-icon {
  width: 50px;
  height: 50px;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  margin-bottom: 12px;
}

.action-text {
  font-size: 14px;
  color: #303133;
  text-align: center;
}

.system-status-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.status-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 0;
  border-bottom: 1px solid #f0f0f0;
}

.status-item:last-child {
  border-bottom: none;
}

.status-label {
  font-size: 14px;
  color: #606266;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .chart-row {
    grid-template-columns: 1fr;
  }

  .stats-cards {
    grid-template-columns: repeat(2, 1fr);
  }
}

@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
  }

  .stats-cards {
    grid-template-columns: 1fr;
  }

  .bottom-section {
    grid-template-columns: 1fr;
  }

  .quick-actions-grid {
    grid-template-columns: repeat(2, 1fr);
  }

  .realtime-stats {
    grid-template-columns: repeat(2, 1fr);
  }
}

/* 饼图样式 */
.pie-chart-demo {
  position: relative;
  width: 300px;
  height: 300px;
  margin: 0 auto;
}

.pie-chart {
  position: relative;
  width: 100%;
  height: 100%;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.pie-center {
  position: absolute;
  width: 100px;
  height: 100px;
  background: white;
  border-radius: 50%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  z-index: 2;
}

.total-count {
  font-size: 20px;
  font-weight: bold;
  color: #303133;
}

.total-label {
  font-size: 12px;
  color: #909399;
  margin-top: 4px;
}

.pie-segment {
  position: absolute;
  width: 100%;
  height: 100%;
  border-radius: 50%;
}

.segment-label {
  position: absolute;
  font-size: 12px;
  font-weight: 500;
  color: #303133;
  background: rgba(255, 255, 255, 0.9);
  padding: 4px 8px;
  border-radius: 4px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  z-index: 3;
}

.segment-color {
  display: inline-block;
  width: 8px;
  height: 8px;
  border-radius: 2px;
  margin-right: 6px;
}

.no-data {
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .pie-chart-demo {
    width: 250px;
    height: 250px;
  }

  .pie-center {
    width: 80px;
    height: 80px;
  }

  .total-count {
    font-size: 16px;
  }

  .segment-label {
    font-size: 11px;
    padding: 3px 6px;
  }
}
</style>